import 'dart:convert';

import 'package:dict_page_view_plugin/dict_page_view_widget_controller.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'dict_page_view_plugin_platform_interface.dart';

/// An implementation of [DictPageViewPluginPlatform] that uses method channels.
class MethodChannelDictPageViewPlugin extends DictPageViewPluginPlatform {
  MethodChannelDictPageViewPlugin() {
    methodChannel.setMethodCallHandler((call) async {
      if (call.arguments is String) {
        final args = jsonDecode(call.arguments);
        int id = args['id'];
        final controller = DictPageViewWidgetController.s_controllers[id];
        if (controller != null && controller.handler != null) {
          return await controller.handler!(call.method, args);
        }
      }

      return null;
    });
  }
  
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('dict_page_view_plugin');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<void> loadUrl(int id, int tabIndex, String url) async {
    await methodChannel.invokeMethod('loadUrl', jsonEncode({
      "id": id,
      "tabIndex": tabIndex,
      "url": url
    }));
  }

  @override
  Future<void> changeTab(int id, int tabIndex) async {
    await methodChannel.invokeMethod('changeTab', jsonEncode({
      "id": id,
      "tabIndex": tabIndex
    }) );
  }

  @override
  Future<Uint8List?> takePhoto(int id, int tabIndex) async {
    final imgData = await methodChannel.invokeMethod('takePhoto', jsonEncode({
      "id": id,
      "tabIndex": tabIndex
    }));
    return imgData;
  }

  @override
  Future<void> loadTabs(int id, List<dynamic> info) async {
    await methodChannel.invokeMethod('loadTabs', jsonEncode({
      "id": id,
      "info": info
    }));
  }
}
